package com.sunday.common.mongo.study.aggregate.tools;

import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.aggregation.EvaluationOperators.Expr;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.Arrays;

public class SpringMongoGenerateTools {

    public static Aggregation generate() {

        AggregationOperation userRole$match = Aggregation.match(Criteria.where("user_id").is(1646819445571584043L));
        AggregationOperation userRole$group = Aggregation.group("user_id").addToSet("role_id").as("role_ids");

        AggregationOperation rolePermissions$lookup = new LookupJoinOperation(
                "sunday_role_permissions",
                new Document("role_ids", "$role_ids"),
                new AggregationPipeline(
                        Arrays.asList(
                                Aggregation.match(Expr.valueOf(AggregationSpELExpression.expressionOf("and(in($role_id,$$role_ids))"))),
                                Aggregation.group("permissions_id")
                        )),
                "permission_ids");

        AggregationOperation permissions$lookup = new LookupJoinOperation(
                "sunday_permissions",
                new Document("permission_id", "$permission_ids._id"),
                new AggregationPipeline(
                        Arrays.asList(
                                Aggregation.match(Expr.valueOf(AggregationSpELExpression.expressionOf("and(in($_id,$$permission_id))"))),
                                Aggregation.project("category", "url", "position", "code")
                        )),
                "permissions");

        AggregationOperation all$unset = UnsetOperation.unset("role_ids", "permission_ids");

        return Aggregation.newAggregation(
                userRole$match,
                userRole$group,
                rolePermissions$lookup,
                permissions$lookup,
                all$unset);
    }

}
